package com.xm.servlet.reception_desk.login;

import com.xm.exception.SqlErrorException;
import com.xm.service.reception_desk.AccountService;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;


/**
 * 登陆页面
 * @author 康文程
 * @date 2023-12-13 上午 08:13
 */
@WebServlet("/account")
public class AccountServlet extends HttpServlet {
    private final AccountService service = new AccountService();

    /**
     * 登陆
     * @param req   an {@link HttpServletRequest} object that
     *                  contains the request the client has made
     *                  of the servlet
     *
     * @param resp  an {@link HttpServletResponse} object that
     *                  contains the response the servlet sends
     *                  to the client
     *
     */
    @SneakyThrows(Exception.class)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        String password = req.getParameter("password");
        String failure = "-1";
        try {
            String account = String.valueOf(service.checkAccount(id, password));
            if (!failure.equals(account)){
                //生成令牌
                String token = UUID.randomUUID().toString();

                System.out.println(token);
                HttpSession scope = req.getSession();
                // 令牌时效时间 8个小时
                scope.setMaxInactiveInterval(60 * 60 * 8);
                //存令牌和账号
                scope.setAttribute("token", token);
                scope.setAttribute("account",account);
                //传回
                resp.getWriter().println(account);
            }else{
                //传回
                resp.getWriter().println("-1");
            }
        } catch (SqlErrorException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 手机号是否已经存在
     * @param req   an {@link HttpServletRequest} object that
     *                  contains the request the client has made
     *                  of the servlet
     *
     * @param resp  an {@link HttpServletResponse} object that
     *                  contains the response the servlet sends
     *                  to the client
     *
     */
    @SneakyThrows(Exception.class)
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        String phone = req.getParameter("phone");
        System.out.println(phone);
        resp.getWriter().println(service.checkPhoneExist(phone));
    }

}
